package com.micromall.repository;

import com.github.pagehelper.Page;
import com.micromall.repository.entity.Order;
import com.micromall.repository.entity.admin.AdminListViewOrder;
import com.micromall.repository.entity.admin.AdminOrderDetail;
import com.micromall.service.vo.ListViewOrder;
import com.micromall.utils.Condition;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.ResultType;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Repository
public interface OrderMapper extends BaseMapper<Order> {

	List<Map<String, Object>> distributionOrderAmountSum(@Param("uid") int uid, @Param("level") int level);

	Page<ListViewOrder> selectListViewPageByWhereClause(Condition build, RowBounds rowBounds);

	Order selectOneByWhereClause(Condition condition);

	@Deprecated
	int deleteByPrimaryKey(Object id);

	@Deprecated
	int deleteByWhereClause(Condition condition);

	@Deprecated
	Order selectByPrimaryKey(Object id);

	@Deprecated
	List<Order> selectMultiByWhereClause(Condition condition);

	@Deprecated
	Page<Order> selectPageByWhereClause(Condition condition, RowBounds bounds);

	@Deprecated
	int countByWhereClause(Condition condition);

	List<Map<String, Object>> statisticsUserOrderCount(int uid);

	@Select("select count(*) from orders where uid=#{uid} and status in(1,2,3,4)")
	int statMemberOrderCount(@Param("uid") int uid);

	Page<AdminListViewOrder> selectAdminPage(Map<String, Object> params, RowBounds rowBounds);

	AdminOrderDetail selectAdminDetail(String orderNo);

	@Update("UPDATE `orders` SET `status` = 5, `update_time` = #{date}, `close_time` = #{date}, `closelog` = '超时未支付关闭订单' WHERE `status` = 0 AND "
			+ "#{date} > `timeout_close_time`")
	int closeTimeoutNotPayOrders(@Param("date") Date date);

	@Update("UPDATE `orders` SET `status` = 3, `confirm_delivery_time` = #{date} WHERE `status` = 2 AND #{date} > date_add(`delivery_time`, "
			+ "interval #{day} day)")
	int ordersAutoConfirmDelivery(@Param("day") int day, @Param("date") Date date);

	@Select("SELECT order_no orderNo,uid,total_amount totalAmount FROM orders WHERE `status` = 3 AND settle = 0 AND #{date} > DATE_ADD"
			+ "(`confirm_delivery_time`, INTERVAL #{day} day)")
	@ResultType(Order.class)
	List<Order> findSettleOrders(@Param("day") int day, @Param("date") Date date);

	@Update("UPDATE `orders` SET `settle` = #{settle}, `settle_time` = #{date}, `update_time` = #{date} WHERE order_no = #{orderNo} AND `status` ="
			+ " 3 AND settle " + "= 0")
	int updateSettleStatus(@Param("orderNo") String orderNo, @Param("settle") int settle, @Param("date") Date date);
}